<?php

namespace App\Http\Controllers;

use App\Models\ScoreInfo;
use App\Models\ScoreLog;
use App\Models\ScoreRule;
use App\Models\UserLibraryInfo;
use Exception;

/**
 * 积分规则模块
 * Class ScoreRule
 * @package app\common\controller
 */
class ScoreRuleController
{
    public $model = null;
    public $scoreLogModel = null;
    public $libraryInfoModel = null;
    public function __construct()
    {
        $this->model = new ScoreInfo();
        $this->scoreLogModel = new ScoreLog();
        $this->libraryInfoModel = new UserLibraryInfo();
    }



    /**
     * 积分规则
     */
    public function lists()
    {
        $res = $this->model->select('id', 'type_name', 'score', 'number', 'intro')->where('is_open', 1)->get()->toArray();

        $controllerObj = new  Controller();
        if ($res) {
            return $controllerObj->returnApi(200, '获取成功', true, $res);
        }
        return $controllerObj->returnApi(202, '获取失败');
    }


    /**
     * 获取自定义积分规则
     */
    public function customScoreRule()
    {
        $scoreRuleModel = new ScoreRule();
        $res = $scoreRuleModel->select('id', 'intro')->first();

        $controllerObj = new Controller();
        if ($res) {
            return $controllerObj->returnApi(200, '获取成功', true, $res);
        }
        return $controllerObj->returnApi(202, '获取失败');
    }


    /**
     * 根据类型获取积分
     * @parma type
     */
    public function getScoreByType($type)
    {
        return $this->model->where('type', $type)->where('is_open', 1)->first();
    }



    /**
     * 判断是否需要操作积分
     * @param  $is_direct 是否直接处理，不管积分是否为负分,直接不判断用户积分够不够 true 不判断  false  要判断
     * @return 200 可以操作积分  201 无须操作积分  202 报错
     */
    public function checkScoreStatus($type, $account_id = null, $is_direct = false)
    {

        //判断读者证号密码是否正确 和是否绑定读者证
        /*  $userLibraryInfoModel = new UserLibraryInfoModel();
          try{
              $account_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id , $account_id);
              $account_id = $account_id ? $account_id : $account_info['id'];
          }catch (\Exception $e){
              return ['code' => 204, 'msg' => $e->getMessage()];//独立状态码，读者证号密码错误
          }*/

        $score_info = $this->getScoreByType($type);

        if (!$score_info) {
            return ['code' => 201, 'msg' => '无效积分规则']; //没有规格，不操作
        }

        //不操作积分
        if (empty($score_info->score)) {
            return ['code' => 201, 'msg' => '无须操作积分'];
        }

        $user_info = $this->libraryInfoModel->find($account_id);

        if (!$user_info) {
            throw new Exception('无效用户信息', 2002);
        }

        /**检查次数限制 */
        if ($score_info->number > 0) {
            $date = date("Y-m-d");
            $count = $this->scoreLogModel->where('account_id', $account_id)->where('type_id', $type)->where(function ($query) use ($date) {
                $query->whereRaw("DATE_FORMAT(`create_time`,'%Y-%m-%d') = '$date'");
            })->count();

            if ($count >= $score_info->number) {
                return ['code' => 201, 'msg' => '今天积分操作次数已满'];
            }
        }
        $new_user_score =  $user_info->score + $score_info->score;

        //不管积分是正是负，都可以处理
        if (!$is_direct) {
            if (!empty($new_user_score) && $new_user_score < 0 && $new_user_score < 0) {
                throw new Exception('积分不足，操作失败', 202);
            }
        }

        return ['code' => 200, 'msg' => '', 'score_info' => $score_info->toArray()];
    }

    /**
     * 判断是否需要操作积分
     * @param  $is_direct 是否直接处理，不管积分是否为负分,直接不判断用户积分够不够 true 不判断  false  要判断
     * @return 200 可以操作积分  201 无须操作积分  202 报错
     */
    public function checkScoreStatusReturnBoole($type, $account_id = null, $is_direct = false)
    {
        $score_info = $this->getScoreByType($type);

        if (!$score_info) {
            //  return false;//没有规格，不操作
            return true; //没有规格，不操作  2022.9.21修改
        }

        //不操作积分
        if (empty($score_info->score)) {
            return true;
        }

        $user_info = $this->libraryInfoModel->find($account_id);

        if (!$user_info) {
            return false;
        }

        /**检查次数限制 */
        if ($score_info->number > 0) {
            $date = date("Y-m-d");
            $count = $this->scoreLogModel->where('account_id', $account_id)->where('type_id', $type)->whereRaw("DATE_FORMAT(`create_time`,'%Y-%m-%d') = '$date'")->count();

            if ($count >= $score_info->number) {
                return true;
            }
        }
        $new_user_score =  $user_info->score + $score_info->score;

        //不管积分是正是负，都可以处理
        if (!$is_direct) {
            if (!empty($new_user_score) && $new_user_score < 0 && $new_user_score < 0) {
                return false;
            }
        }

        return true;
    }


    /**
     * 操作积分 除商品外
     * @param  $is_direct 是否直接处理，不管积分是否为负分
     */
    public function scoreChange($score_info, $account_id = null, $system_id = 0)
    {
        $user_info = $this->libraryInfoModel->find($account_id);

        if (!$user_info) {
            throw new Exception('无效用户信息', 202);
        }

        //修改用户积分
        $user_info->score =  $user_info->score + $score_info['score_info']['score'];
        $user_info->save();

        /**记录积分log */
        $log_data = [
            'account_id' => $account_id,
            'system_id' => $system_id,
            'score' => $score_info['score_info']['score'],
            'type_id' => $score_info['score_info']['id'],
            'type' => $score_info['score_info']['type_name'],
            'intro' => $score_info['score_info']['intro'],
            'create_time' => date("Y-m-d H:i:s")
        ];

        $this->addScoreLog($log_data);

        return ['code' => 200, 'msg' => '积分操作成功'];
    }

    /**
     * 积分退还 除商品外
     */
    public function scoreReturn($type, $score, $account_id = null, $intro = null, $system_id = 0, $title = '')
    {
        $score_rule = $this->model->where('type', $type)->first();

        $user = $this->libraryInfoModel->find($account_id);

        if (!$user) {
            throw new Exception('无效用户信息', 2002);
        }

        $score *= -1; //改变积分符号

        $user->score =  $user->score + $score;
        $user->save();

        /**记录积分log */
        $log_data = [
            'account_id' => $account_id,
            'system_id' => $system_id,
            'score' => $score,
            'type_id' => !empty($score_rule['id']) ? $score_rule['id'] : 0,
            'type' => !empty($title) ? $title : $score_rule['type_name'],
            'intro' => !empty($intro) ? $intro : '积分回退',
            'create_time' => date("Y-m-d H:i:s")
        ];

        $this->addScoreLog($log_data);

        return ['code' => 200, 'msg' => '积分回退成功'];
    }
    /**
     * 积分字样
     */
    public function getScoreMsg($score)
    {
        return $score > 0 ? '退回' : "返还";
    }

    /**
     * 商品、欠款缴纳积分扣除
     * @param $type_id 类型id  0 为商品   999 为缴纳欠款
     */
    public function scoreGoodChange($score, $account_id = null, $type = null, $msg = null, $system_id = 0, $type_id = 0)
    {
        //判断读者证号密码是否正确 和是否绑定读者证
        // try{
        //     $account_info = $this->libraryInfoModel->checkAccountPwdIsNormal($user_id , $account_id);
        //     $account_id = $account_id ? $account_id : $account_info['id'];
        // }catch (\Exception $e){
        //     return ['code' => 204, 'msg' => $e->getMessage()];//独立状态码，读者证号密码错误
        // }

        $user = $this->libraryInfoModel->find($account_id);

        if (!$user) {
            throw new Exception('无效用户信息', 2002);
        }

        $user->score =  $user->score - $score;
        $user->save();

        /**记录积分log */
        $log_data = [
            'account_id' => $user->id,
            'system_id' => $system_id,
            'score' => $score *= -1,
            'type_id' => $type_id,
            'type' => $type,
            'intro' => $msg,
            'create_time' => date("Y-m-d H:i:s")
        ];

        $this->addScoreLog($log_data);
    }

    /**
     * 商品积分返还
     */
    public function scoreGoodReturn($score, $account_id, $type, $msg, $system_id)
    {
        $user = $this->libraryInfoModel->find($account_id);

        if (!$user) {
            throw new Exception('无效用户信息', 2002);
        }

        $user->score =  $user->score + $score;
        $user->save();

        /**记录积分log */
        $log_data = [
            'account_id' => $account_id,
            'system_id' => $system_id,
            'score' => $score,
            'type_id' => 0,
            'type' => $type,
            'intro' => $msg,
            'create_time' => date("Y-m-d H:i:s")
        ];

        $this->addScoreLog($log_data);
    }
    /**
     *  添加积分信息
     * @parma $data
     */
    public function addScoreLog($data)
    {
        $this->scoreLogModel->account_id = $data['account_id'];
        $this->scoreLogModel->score = $data['score'];
        $this->scoreLogModel->type_id = $data['type_id'];
        $this->scoreLogModel->type = $data['type'];
        $this->scoreLogModel->intro = $data['intro'];
        $this->scoreLogModel->manage_id = !empty(request()->manage_id) ? request()->manage_id : null;

        $this->scoreLogModel->save();
    }
}
